import { reactive, onMounted } from 'vue'
import _ from 'lodash'

export default function useDialog(
  proxy,
  options = {
    open: {
      before: undefined,
      type: undefined,
      title: undefined
    },
    close: { after: undefined },
    submit: {
      action: undefined,
      before: undefined,
      after: undefined,
      validRef: undefined,
      resolveParam: undefined,
      tips: undefined
    }
  }
) {
  const dialogModel = reactive({
    show: false,
    title: '',
    type: '',
    data: {},
    submitLoading: false
  })

  function handleOpen(data) {
    if (_.isFunction(options.open?.before)) {
      options.open.before(data)
    }
    dialogModel.type = options.open.type
    dialogModel.title = _.isFunction(options.open?.title)
      ? options.open.title()
      : options.open.title
    dialogModel.show = true
  }

  function handleSubmit() {
    if (_.isFunction(options.submit?.before)) {
      options.submit.before()
    }
    dialogModel.submitLoading = true
    if (options.submit.validRef) {
      proxy.$refs[options.submit.validRef].validate((valid, prop) => {
        if (!valid) {
          dialogModel.submitLoading = false
          console.warn(prop, 'valid failed')
          return
        }
        doSubmit()
      })
    } else {
      doSubmit()
    }
  }

  function doSubmit() {
    const param = _.isFunction(options.submit?.resolveParam)
      ? options.submit.resolveParam(dialogModel.data)
      : dialogModel.data

    options.submit
      .action(param)
      .then((res) => {
        dialogModel.submitLoading = false
        if (_.isFunction(options.submit?.after)) {
          options.submit.after(res)
        }
        handleClose()
        proxy.$modal.msgSuccess(options.submit.tips || '操作成功!')
      })
      .catch((e) => {
        dialogModel.submitLoading = false
      })
  }

  function handleClose() {
    dialogModel.show = false
    if (_.isFunction(options.close?.after)) {
      options.close.after()
    }
  }

  onMounted(() => {
    console.log('useDialog hook mounted!')
  })

  return {
    dialogModel,
    handleOpen,
    handleClose,
    handleSubmit
  }
}
